import React from 'react';
import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import Login from './pages/Login';
import Home from './pages/Home';
import UserList from './pages/UserList';
import ProductList from './pages/ProductList';
import CategoryList from './pages/CategoryList';
import OrderList from './pages/OrderList';
import BannerList from './pages/BannerList';
import AiInquiryList from './pages/AiInquiryList';
import Layout from './components/Layout';

const RequireAuth: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const location = useLocation();
  const isLogin = localStorage.getItem('isLogin') === '1';
  if (!isLogin && location.pathname !== '/login') {
    return <Navigate to="/login" replace />;
  }
  return <>{children}</>;
};

const App: React.FC = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route
          path="/home"
          element={
            <RequireAuth>
              <Layout>
                <Home />
              </Layout>
            </RequireAuth>
          }
        />
        <Route
          path="/users"
          element={
            <RequireAuth>
              <Layout>
                <UserList />
              </Layout>
            </RequireAuth>
          }
        />
        <Route
          path="/products"
          element={
            <RequireAuth>
              <Layout>
                <ProductList />
              </Layout>
            </RequireAuth>
          }
        />
        <Route
          path="/categories"
          element={
            <RequireAuth>
              <Layout>
                <CategoryList />
              </Layout>
            </RequireAuth>
          }
        />
        <Route
          path="/orders"
          element={
            <RequireAuth>
              <Layout>
                <OrderList />
              </Layout>
            </RequireAuth>
          }
        />
        <Route
          path="/banners"
          element={
            <RequireAuth>
              <Layout>
                <BannerList />
              </Layout>
            </RequireAuth>
          }
        />
        <Route
          path="/ai-inquiry"
          element={
            <RequireAuth>
              <Layout>
                <AiInquiryList />
              </Layout>
            </RequireAuth>
          }
        />
        <Route path="*" element={<Navigate to="/home" replace />} />
      </Routes>
    </BrowserRouter>
  );
};

export default App;
